package epoch.game.core.common;

import java.util.concurrent.atomic.AtomicLong;

import org.apache.logging.log4j.Logger;

/**
 * 时间统计工具
 * 
 * @author will
 * @date 2015年7月13日 下午8:31:54
 */
public final class TimeStat {
	
	public static volatile boolean open = true;

	private static Logger log = Loggers.TIME_STAT_LOGGER;
	
	public static AtomicLong counter = new AtomicLong();
	//默认统计最短时间(ms)	
	public static long DEFAULT_TIME_OUT=50;

	/**
	 * 新建一个统计对象
	 * @param timeout 统计的最小时长（ms）
	 * @return
	 */
	public static TimeStat newInstance(long timeout) {
		return new TimeStat(timeout);
	}
	
	/**
	 * 默认统计时间为50ms
	 * @return
	 */
	public static TimeStat newInstance(){
		return new TimeStat(DEFAULT_TIME_OUT);
	}

	private long timeout;
	private long beginTime;
	
	private TimeStat(){
		beginTime = System.currentTimeMillis();
	}

	private TimeStat(long timeout) {
		beginTime = System.currentTimeMillis();
		this.timeout = timeout;
	}
	
	/**
	 * 重置开始统计时间
	 */
	public void reset(){
		beginTime = System.currentTimeMillis();
	}
	
	/**
	 * 统计超时数据
	 * @param info
	 */
	public void stat(String info) {
		if (open) {
			long passTime = System.currentTimeMillis()-beginTime;
			if(passTime>timeout){
				log.info(info + " 耗时：" + passTime + "ms");
			}
		}
	}
	
	
	
	/**
	 * 统计超时数据并且重置开启统计时间
	 * @param info
	 */
	public void statAndReset(IDelayBuildInfo infoBuilder) {
		if (open) {
			long passTime = System.currentTimeMillis()-beginTime;
			if(passTime>timeout){
				log.info(infoBuilder.getInfo() + " 耗时：" + passTime + "ms");
			}
			beginTime = System.currentTimeMillis();
		}
	}
	
	/**
	 * 统计超时数据并且重置开启统计时间
	 * @param info
	 */
	public void statAndReset(String info) {
		if (open) {
			long passTime = System.currentTimeMillis()-beginTime;
			if(passTime>timeout){
				log.info(info + " 耗时：" + passTime + "ms");
			}
			beginTime = System.currentTimeMillis();
		}
	}

}
